package cn.chengpengper.unit17.server.handler;

import cn.chengpengper.unit17.protocol.request.MessageRequestPacket;
import cn.chengpengper.unit17.protocol.response.MessageResponsePacket;
import cn.chengpengper.unit17.protocol.session.Session;
import cn.chengpengper.unit17.util.SessionUtil;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

import java.util.Date;
/*@formatter:off*/

/**
 * ____________________
 * _                _                                                           < 神兽护体，永无bug! >
 * | |__  _   _  ___| |__   ___ _ __   __ _ _ __   ___ _ __   __ _                --------------------
 * | '_ \| | | |/ __| '_ \ / _ \ '_ \ / _` | '_ \ / _ \ '_ \ / _` |                       \   ^__^
 * | | | | |_| | (__| | | |  __/ | | | (_| | |_) |  __/ | | | (_| |                        \  (oo)\_______
 * |_| |_|\__,_|\___|_| |_|\___|_| |_|\__, | .__/ \___|_| |_|\__, |                           (__)\       )\/\
 * |___/|_|               |___/                                ||----w |
 * ||     ||
 *
 * @author huchengpeng
 * @version v1.0.0
 * @date 2024/4/10 23:38
 * @description 消息处理器
 */

/*@formatter:on*/

public class MessageRequestPacketHandler extends SimpleChannelInboundHandler<MessageRequestPacket> {
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, MessageRequestPacket messageRequestPacket) throws Exception {
        System.out.println(new Date() + " :收到客户端消息" + messageRequestPacket.getMessage());
        // 获得消息发送方的会话信息
        Session session = SessionUtil.getSession(ctx.channel());

        // 通过消息发送方的会话信息构造要发送的消息
        MessageResponsePacket messageResponsePacket = new MessageResponsePacket();
        messageResponsePacket.setFromUserId(session.getUserId());
        messageResponsePacket.setFromUserName(session.getUserName());
        messageResponsePacket.setMessage(messageRequestPacket.getMessage());

        // 获取消息接收方的 Channel
        Channel channel = SessionUtil.getChannel(messageRequestPacket.getToUsrId());

        // 将消息发送给消息接收方
        if (channel != null && SessionUtil.hasLogin(channel)) {
            channel.writeAndFlush(messageResponsePacket);
        } else {
            System.out.println(messageRequestPacket.getToUsrId() + "不在线，发送失败");
        }
    }
}
